package com.example.controller;

import cn.hutool.json.JSONUtil;
import com.example.common.R;
import com.example.mapper.VacateMapper;
import com.example.pojo.Vacate;
import com.example.util.ExcelUtil;
import com.example.util.RedisUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author ：伍绍恒
 * @date ：Created in 2022/12/12 17:18
 * @description：
 * @modified By：
 */
@ResponseBody
@Controller
@RequestMapping("/vacate")
public class VacateController {
    @Resource
    VacateMapper vacateMapper;
    @Resource
    RedisUtil redisUtil;

    @GetMapping("/getAll")
    public R<PageInfo> getAll(int page, int pageSize, String name) {
        PageHelper.startPage(page, pageSize, true);
        final PageInfo pageInfo = new PageInfo(vacateMapper.getAll(name));
        return R.success(pageInfo);
    }

    @GetMapping("/getAllData")
    public R<PageInfo> getAllData() {
        List<Vacate> allVacate = null;
        String json = (String) redisUtil.get("sx:vacateAllData");
        if (json != null) {//有缓存
            allVacate = JSONUtil.toList(json, Vacate.class);
        } else {//无缓存
            //查询数据库
            allVacate = vacateMapper.getAll(null);
            //保存到缓存
            redisUtil.set("sx:vacateAllData", JSONUtil.toJsonStr(allVacate), 10);
        }
        final PageInfo pageInfo = new PageInfo(allVacate);
        return R.success(pageInfo);
    }

    @DeleteMapping()
    public R<String> deletes(String[] ids) {
        int deleteCount = vacateMapper.deleteByIds(ids);
        if (deleteCount == 0) {
            return R.error("删除失败！");
        }
        //删除旧缓存
        redisUtil.del("sx:vacateAllData");
        return R.success("批量删除成功！");
    }

    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        List<Vacate> all = vacateMapper.getAll(null);
        new ExcelUtil().export("vacate", all, response);
    }

    @PostMapping("/handleStatus")
    public R<String> changStatus(@RequestParam("wid") String[] ids, @RequestParam("status") String status) {
        int changeCount = vacateMapper.changeStatus(ids, status);
        if (changeCount == 0) {
            return R.error("修改失败");
        }
        //删除旧缓存
        redisUtil.del("sx:vacateAllData");
        return R.success("修改成功！");
    }
}
